//
//  ViewController.swift
//  AppHelper
//
//  Created by Apple on 2018/1/26.
//  Copyright © 2018年 Apple. All rights reserved.
//

import Cocoa


class ViewController: NSViewController {
    
    @IBOutlet weak var originalImageView: NSImageView!
    
    @IBOutlet weak var iPhoneCheckBox: NSButton!
    @IBOutlet weak var iPadCheckBox: NSButton!
    
    @IBOutlet weak var portraitCheckBox: NSButton!
    @IBOutlet weak var landscapeBox: NSButton!
    
    @IBOutlet var logTextView: NSTextView!
    
    /// iPhone
    private var isIPhone: Bool {
        return iPhoneCheckBox.state == .on
    }
    /// iPad
    private var isIPad: Bool {
        return iPadCheckBox.state == .on
    }
    
    /// 竖屏
    private var isPortrait: Bool {
        return portraitCheckBox.state == .on
    }
    /// 横屏
    private var isLandscape: Bool {
        return landscapeBox.state == .on
    }
    
    private var baseSavePath: String? = nil
    /// 日志编号
    private var logNum: Int = 0
    
    enum ImageType {
        case iPhone
        case iPad
    }
    enum ImageDirection: String {
        case portrait = "竖屏"
        case landscape = "横屏"
    }
    
    struct ImageInfo {
        /// 图片名称
        var name: String
        var size: NSSize
        var type: ImageType
        var direction: ImageDirection
    }
    
    
    // MARK: - LaunchImage
    /// name规范命名方法：
    /// LaunchImage-版本-P/L(P: 竖屏, L: 横屏)-高度(竖直高度 / 缩放)@缩放(如果为1，则省略@1x)
    var launchImageInfos: [ImageInfo] = [
        // iPhone 竖屏
        ImageInfo(name: "LaunchImage-1-P-812@3x",
                  size: NSSize(width: 1125, height: 2436),
                  type: .iPhone,
                  direction: .portrait),
        ImageInfo(name: "LaunchImage-1-P-736@3x",
                  size: NSSize(width: 1242, height: 2208),
                  type: .iPhone,
                  direction: .portrait),
        ImageInfo(name: "LaunchImage-1-P-667@2x",
                  size: NSSize(width: 750, height: 1334),
                  type: .iPhone,
                  direction: .portrait),
        ImageInfo(name: "LaunchImage-1-P-568@2x",
                  size: NSSize(width: 640, height: 1136),
                  type: .iPhone,
                  direction: .portrait),
        ImageInfo(name: "LaunchImage-1-P-480@2x",
                  size: NSSize(width: 640, height: 960),
                  type: .iPhone,
                  direction: .portrait),

        // iPhone 横屏
        ImageInfo(name: "LaunchImage-1-L-812@3x",
                  size: NSSize(width: 2436, height: 1125),
                  type: .iPhone,
                  direction: .landscape),
        ImageInfo(name: "LaunchImage-1-L-736@2x",
                  size: NSSize(width: 2208, height: 1242),
                  type: .iPhone,
                  direction: .landscape),
        
        
        // iPad 竖屏
        ImageInfo(name: "LaunchImage-1-P-1024@2x",
                  size: NSSize(width: 1536, height: 2048),
                  type: .iPad,
                  direction: .portrait),
        ImageInfo(name: "LaunchImage-1-P-1024",
                  size: NSSize(width: 768, height: 1024),
                  type: .iPad,
                  direction: .portrait),
        
        // iPad 横屏
        ImageInfo(name: "LaunchImage-1-L-1024@2x",
                  size: NSSize(width: 2048, height: 1536),
                  type: .iPad,
                  direction: .landscape),
        ImageInfo(name: "LaunchImage-1-L-1024",
                  size: NSSize(width: 1024, height: 768),
                  type: .iPad,
                  direction: .landscape)
    ]
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

    @IBAction func cleanLog(_ sender: Any) {
        logTextView.string = ""
    }
    
    @IBAction func handleButton(_ sender: Any) {
        guard let originImg = originalImageView.image else {
            log("Tips: 请将原始图片拖放到图片框内")
            return
        }
        
        guard isIPhone || isIPad else {
            log("Tips: 至少选择一种类型->【iPhone】、【iPad】、【iPhone + iPad】")
            return
        }
        
        // 选择文件输入路径
        chooseSavePath { path in
            self.log("输出路径：\(path)")
            self.log("原始图片大小: \(originImg.size)")
            
            self.baseSavePath = path
            self.handleImage(originImg)
        }
    }
    
    func chooseSavePath(_ success: @escaping (_ path: String) -> Void) {
        let openPanel = NSOpenPanel()
        openPanel.allowsOtherFileTypes = false              // 不允许其它文件类型
        openPanel.treatsFilePackagesAsDirectories = false   // 不允许文件包作为文件夹
        openPanel.canChooseFiles = false    // 不允许选择文件
        openPanel.canChooseDirectories = true   // 允许选择文件夹
        openPanel.canCreateDirectories = true   // 允许创建文件夹
        openPanel.prompt = "确定" // 按钮名称
        openPanel.begin { modalResponse in

            if modalResponse == .OK {
                success(openPanel.url!.path)
            } else {
                self.log("用户取消选择输出路径")
            }
        }
    }
    
    func handleImage(_ originImg: NSImage) {
        
        var imgInfos: [ImageInfo] = launchImageInfos
        
        // 只有iPhone
        if isIPhone && !isIPad {
            imgInfos = imgInfos.filter { $0.type == .iPhone }
        }
        // 只有iPad
        else if isIPad && !isIPhone {
            imgInfos = imgInfos.filter { $0.type == .iPad }
        }
        
        // 只有竖屏
        if isPortrait && !isLandscape {
            imgInfos = imgInfos.filter { $0.direction == .portrait }
        }
        // 只有横屏
        else if isLandscape && !isPortrait {
            imgInfos = imgInfos.filter { $0.direction == .landscape }
        }
        
        handleImage(originImg, to: imgInfos)
    }
    
    func handleImage(_ originImg: NSImage, to imageInfos: [ImageInfo]) {
        imageInfos.forEach { info in
            guard let img = originImg.tailor(toSize: info.size) else {
                log("切图失败")
                return
            }
            self.save(image: img, fileName: info.name)
        }
    }
    
    func save(image: NSImage, fileName: String, fileExtension: String = "png") {
        guard let baseSavePath = baseSavePath else { return }
        let path = "\(baseSavePath)/\(fileName).\(fileExtension)"
        
        // 文件管理器
        let fileMgr = FileManager.default
        // 文件已经存在
        if fileMgr.fileExists(atPath: path) {
            log("文件存在：\(path)")
            return
        }
        
        let isSuccess = image.writePNG(to: path)
        log("\(fileName): \(isSuccess ? "成功" : "失败")")
    }
    
    func log(_ msg: String) {
        logTextView.string += msg + "\n"
        logTextView.scrollToEndOfDocument(nil)
    }
}

